package com.huihui.activity.login;

import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.huihui.R;
import com.huihui.base.BaseActivity;
import com.huihui.datamanager.AppManager;
import com.huihui.network.HttpContants;
import com.huihui.network.OkHttpRequest;
import com.huihui.network.base.CallBackUtil;
import com.huihui.network.pojo.UserInfo;
import com.huihui.utils.IntentUtils;
import com.huihui.utils.StringUtils;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;

/**
 * 注册页
 */
public class RegisterActivity extends BaseActivity {

    private EditText input_phone;
    private EditText input_psw;
    private TextView get_sms;
    private TextView login;

    private boolean mIsPhoneValid;
    private int mCount = 60;


    private Runnable mCountDownRunnable = new Runnable() {
        @Override
        public void run() {
            if (mCount > 0) {
                get_sms.setText(getString(R.string.control_get_code_counter, mCount--));
                UIHandler.postDelayed(mCountDownRunnable, 1000);
            } else {
                mCount = 60;
                get_sms.setText(getString(R.string.get_sms));
                if (mIsPhoneValid) {
                    get_sms.setEnabled(true);
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
//        getSupportActionBar().setTitle(R.string.register);
        titleView.setText(R.string.register);
        initView();
        initListener();
    }

    private void initListener() {

        input_phone.addTextChangedListener(new TextWatcher() {


            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (StringUtils.isPhone(input_phone.getText().toString())) {
                    if (mCount > 0 && mCount < 60) {
                        mIsPhoneValid = false;
                        get_sms.setEnabled(false);
                    } else {
                        mIsPhoneValid = true;
                        get_sms.setEnabled(true);
                    }
                } else {
                    mIsPhoneValid = false;
                    get_sms.setEnabled(false);
                }

            }
        });

        get_sms.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取验证码
                String inputPhone = input_phone.getText().toString();
                if (!StringUtils.isPhone(inputPhone)) {
                    Toast.makeText(getContext(),R.string.error_phone_not_match,Toast.LENGTH_SHORT).show();
                    return;
                }
                get_sms.setEnabled(false);
                get_sms.setText(getString(R.string.control_get_code_counter, mCount--));
                //获取验证码请求
                    OkHttpRequest.getInstance().sendSmsCode(HttpContants.sendSmsCode, 0, input_phone.getText().toString(), 1, new CallBackUtil.CallBackString() {
                    @Override
                    public void onFailure(Call call, Exception e) {
                        get_sms.setEnabled(true);
                        mCount = 60;
                        get_sms.setText(getString(R.string.get_sms));
                        UIHandler.removeCallbacks(mCountDownRunnable);
                    }

                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject json = new JSONObject(response);
                            if(json.has(HttpContants.MSG)){
                                Toast.makeText(getContext(), json.getString(HttpContants.MSG),Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
                UIHandler.postDelayed(mCountDownRunnable, 1000);
            }
        });

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String inputPhone = input_phone.getText().toString();
                //登陆
                if (!StringUtils.isPhone(inputPhone)) {
                    Toast.makeText(getContext(),R.string.error_phone_not_match,Toast.LENGTH_SHORT).show();
                    return;
                }
                OkHttpRequest.getInstance().register(HttpContants.register, inputPhone, input_psw.getText().toString(), new CallBackUtil.CallBackString() {
                    @Override
                    public void onFailure(Call call, Exception e) {
                        Toast.makeText(getContext(), R.string.login_fail,Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject json = new JSONObject(response);
                            if(json.has(HttpContants.STATE) && json.getInt(HttpContants.STATE) == 10000) {
                                if (json.has(HttpContants.DATA)) {
                                    UserInfo userInfo = AppManager.getGson().fromJson(json.getString(HttpContants.DATA), UserInfo.class);
                                    if (userInfo != null) {
                                        setUserInfo(userInfo);
                                        AppManager.setUserInfo(userInfo);
                                        AppManager.setToken(userInfo.getToken());
                                        IntentUtils.gotoMainActivity(getContext());
                                        finish();
                                    }
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
    }

    private void initView() {
        input_phone = (EditText) findViewById(R.id.input_phone);
        input_psw = (EditText) findViewById(R.id.input_psw);
        get_sms = (TextView) findViewById(R.id.get_sms);
        login = (TextView) findViewById(R.id.login);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UIHandler.removeCallbacks(mCountDownRunnable);
    }
}
